package com.kyle.pagingdemo.paging

import androidx.paging.ExperimentalPagingApi
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.kyle.pagingdemo.IApi
import com.kyle.pagingdemo.data.model.Post
import com.kyle.pagingdemo.room.ArticleDatabase
import kotlinx.coroutines.flow.Flow

class PostRepository(private val api: IApi, private val db: ArticleDatabase) {

    @OptIn(ExperimentalPagingApi::class)
    fun getPosts(): Flow<PagingData<Post>> =  Pager(
        config = PagingConfig(
            // 每页显示的数据的大小。对应 PagingSource 里 LoadParams.loadSize
            pageSize = 20,

            // 预刷新的距离，距离最后一个 item 多远时加载数据，默认为 pageSize
            prefetchDistance = 5,

            enablePlaceholders = false,

            // 初始化加载数量，默认为 pageSize * 3
            initialLoadSize = 60

            // 一次应在内存中保存的最大数据，默认为 Int.MAX_VALUE
//            maxSize = 200
        ),
        remoteMediator = ArticleRemoteMediator(api, db)
    ){
        db.articleDao().allPost()
    }.flow

}